﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Pahan.McuFusion.Common.Utils
{
    internal class AssemblyResolutionScope : IDisposable
    {
        public AssemblyResolutionScope()
        {
            AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
        }

        public void Dispose()
        {
            AppDomain.CurrentDomain.AssemblyResolve -= OnAssemblyResolve;
        }

        private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
        {
            var assemblies = AssemblyLoader.GetAssemblies();

            // First try to find assembly by exact name.
            foreach (var assembly in assemblies)
            {
                if (assembly.FullName == args.Name)
                {
                    return assembly;
                }
            }

            // Then try to find by partial name.
            var partialName = new AssemblyName(args.Name).Name;
            foreach (var assembly in assemblies)
            {
                if (assembly.GetName().Name == partialName)
                {
                    return assembly;
                }
            }
            return null;
        }
    }
}
